//index.js

// 状态码映射
import store from "../store";

const statusCode = {
	ok: 0,
	401: 'NOTOKEN'
}

class Http {
	constructor(config = {}) {
		// 合并配置
		this.config = {
			baseURL: 'http://ruoyigateway.cpolar.top',
			timeout: 0,
			headers: {
				'Content-Type': 'application/json'
			},
			...config
		}

		// 拦截器存储
		this.interceptors = {
			request: [],
			response: []
		}
	}

	// 添加拦截器
	useInterceptor(type, fulfilled, rejected) {
		this.interceptors[type].push({
			fulfilled,
			rejected
		})
	}

	// 核心请求方法
	async request(options) {
		// 合并配置
		const mergedConfig = {
			...this.config,
			...options,
			url: this.config.baseURL + options.url,
			header: {
				...this.config.headers,
				...(options.header || {})
			}
		}

		// 执行请求拦截器
		let requestConfig = mergedConfig
		for (const interceptor of this.interceptors.request) {
			try {
				requestConfig = await interceptor.fulfilled(requestConfig) || requestConfig
			} catch (err) {
				interceptor.rejected(err)
				throw err
			}
		}

		// 发起请求
		let response

		try {
		  const res = await uni.request(requestConfig);
		  response = res;
		} catch (error) {
		  // 统一处理请求错误（如网络问题）
		  for (const interceptor of this.interceptors.response) {
		    if (typeof interceptor.rejected === 'function') {
		      interceptor.rejected(error);
		    }
		  }
		  throw error;
		}

		// 执行响应拦截器
		for (const interceptor of this.interceptors.response) {
			try {
				response = await interceptor.fulfilled(response) || response
			} catch (err) {
				if (typeof interceptor.rejected === 'function') {
					interceptor.rejected(err)
				}
				throw err
			}
		}
		return response
	}

	// 快捷方法
	get(url, params, options = {}) {
		return this.request({url,method: 'GET',data: params,...options})
		}
	post(url, data, options = {}) {return this.request({url,method: 'POST',data,...options})}
	put(url, data, options = {}) {return this.request({url,method: 'PUT',data,...options})}
	delete(url, data, options = {}) {return this.request({url,method: 'DELETE',data,...options})}
}

// 创建实例
const createInstance = (config) => {
	const instance = new Http(config)

	// 添加默认请求拦截器
	instance.useInterceptor('request', (config) => {
		// 添加loading
		uni.showLoading({
			title: '加载中...',
			mask: true
		})

		// 添加token（根据实际存储方式调整）
		// const token = uni.getStorageSync('token') // 示例获取token方式
		// if (token) {
		// 	config.header.Authorization = `Bearer ${token}`
		// }
		console.log("是否已登录",store.getters["token/getIsLogin"])
		console.log("httpIndex.token",store.getters["token/getToken"])
		if (store.getters["token/getIsLogin"]){
			config.header.Authorization = `Bearer ${store.getters["token/getToken"]}`
		}

		return config
	}, error => {
		uni.hideLoading()
		return Promise.reject(error)
	})

	// 添加默认响应拦截器
	instance.useInterceptor('response', (response) => {
		console.log("原始数据",response)
		uni.hideLoading()
		const {
			statusCode,
			data
		} = response
		// console.log(data)
		if (statusCode === 200) {
			if (data.code === statusCode.ok) {
				return data
			} else {
				// uni.showToast({
				// 	title: data.message || '请求失败',
				// 	icon: 'none'
				// })
				// return Promise.reject(data)
				return data
			}
		}
		// 处理401等状态码
		if (statusCode === 401) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
		return Promise.reject(response)
	}, error => {
		uni.hideLoading()
		uni.showToast({
			title: '网络异常',
			icon: 'none'
		})
		return Promise.reject(error)
	})

	return instance
}

// 创建默认实例
const request = createInstance({
	baseURL: 'http://ruoyigateway.cpolar.top' // 设置基础路径
})

export default request